<template>
	<el-dialog v-model="visible" :title="(isView ? '查看': !dataForm.id ? '新建' : '编辑')+'采购单'" :close-on-click-modal="false" width="1430px" center destroy-on-close>
		<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="80px" v-loading="pageloading">
            <div class="flex">
                <div>
                    <el-form-item  label="采购时间" prop="time">
                        <el-date-picker
                            v-model="dataForm.time"
                            type="datetime"
                            placeholder="请选择采购时间"

                            format="YYYY-MM-DD HH:mm:ss"
                            value-format="YYYY-MM-DD HH:mm:ss"
                             style="width: 230px;"
                            :disabled="isView"
                        />
                    </el-form-item>
                </div>
                <div class="ml10">
                    <el-form-item  label="采购类型" prop="type">
                        <el-select v-model="dataForm.type" :filterable="canfilterable" clearable placeholder="请输入" :disabled="isView" style="width: 230px;">
                            <el-option label="产品采购" :value="1" />
                            <el-option label="材料采购" :value="2" />
                        </el-select>
                    </el-form-item>
                </div>
            </div>
			<div class="flex">
                <div>
                    <div class="flex">
                        <el-form-item  label="供应商" prop="supplier_name">
                            <el-select v-model="dataForm.supplier_name" :filterable="canfilterable" clearable allow-create placeholder="请输入选择供应商" :disabled="isView" style="width: 230px;">
                                <el-option
                                v-for="item in supplierList"
                                :key="item.id"
                                :label="item.label"
                                :value="item.label"
                                />
                            </el-select>
                        </el-form-item>
                    </div>
                </div>
                <div class="ml10">
                    <el-form-item  label="批次号" prop="batch_no">
                        <el-input v-model="dataForm.batch_no" placeholder="请输入批次号" maxlength="255" style="width: 230px;" :disabled="isView"></el-input>
                    </el-form-item>
                </div>
            </div>
			<div class="flex">
                <div>
                    <div class="flex">
                        <el-form-item  label="分摊人">
                            <el-select v-model="chooseUser" :filterable="canfilterable" multiple clearable allow-create placeholder="请输入选择分摊人" :disabled="isView" style="width: 230px;" @change="handleChangeUser">
                                <el-option
                                v-for="item in departmentList"
                                :key="item.id"
                                :label="item.label"
                                :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </div>
                </div>
                <div>
                    <div class="flex">
                        <el-form-item  label="分摊比例">
                            <div class="w100">
                                <div class="w100" v-for="user,i in chooseUserList" :key="i">
                                    <div class="flex flexL" style="width: 240px;">
                                        <div style="width: 40%;">{{ user.label }}</div>
                                        <div style="width: 60%;">
                                            <el-input v-model="user.rate" placeholder="请输入比例%" :disabled="isView" @input="notNoNumber(user,'rate',$event)" type="number" style="width: 100%;" />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </el-form-item>
                    </div>
                    
                </div>
            </div>
            <div class="flex">
                <div class="flex1">
                    <el-form-item  label="采购备注" prop="remark">
                        <el-input v-model="dataForm.remark" placeholder="请输入备注" maxlength="5000" style="width: 100%;" :disabled="isView"></el-input>
                    </el-form-item>
                </div>
            </div>
			<div class="table-content">
				<table class="table tablec">
					<tr class="tr">
						<td class="td th">*产品</td>
						<td class="td th">属性</td>
						<td class="td th">成本价</td>
						<td class="td th">
                            <span>*采购数量</span>
                        </td>
						<td class="td th">
                            <span>应分摊金额</span>
                        </td>
						<!-- <td class="td th">*进货单价</td>
						<td class="td th">金额</td> -->
                        <td class="td th" v-for="user,i in chooseUserList" :key="i">{{ user.label }}</td>
						<td class="td th" v-if="!isView">操作</td>
					</tr>
					<tr class="tr" v-for="(item,index) in options" :key="item.id">
						<td class="td">
							<el-select v-model="item.productName" placeholder="请输入选择产品" :filterable="canfilterable" style="width: 240px;" :disabled="isView" @change="selectChange(index, $event)">
								<el-option v-for="i in productList" :disabled="disOption(i.label, options[0])" :key="i.value" :label="i.label" :value="i.label" />
							</el-select>
						</td>
						<td class="td">
							<el-select v-model="item.productId" placeholder="请输入选择属性" :filterable="canfilterable" style="width: 240px;" no-data-text="请先选择产品" :disabled="isView" @change="selectChange2(index, $event)">
								<el-option v-for="i in item.attrList" :key="i.value" :label="i.label" :value="i.value" />
							</el-select>
						</td>
						<td class="td">
							{{ item.make_price }}
						</td>
						<td class="td">
							<el-input v-model="item.quantity" placeholder="请输入数量" :disabled="isView" @mousewheel.native.prevent @input="notNoNumber(item,'quantity',$event, setAmount(index))" type="number" style="width: 120px;" />
						</td>
						<td class="td">
							{{ setFtTotal(item) }}
						</td>
						<!-- <td class="td">
							<el-input v-model="item.price" placeholder="请输入单价" :disabled="isView" @input="notNoNumber(item,'price',$event, setAmount(index))" type="number" style="width: 120px;" />
						</td>
						<td class="td">
							<el-input v-model="item.total_price" placeholder="请输入金额" :disabled="isView" @input="notNoNumber(item,'total_price',$event)" type="number" style="width: 120px" />
						</td> -->
                        <td class="td" v-for="user,i in chooseUserList" :key="i">
                            <div style="min-width: 120px;">
                                <div style="width: 100%;" class="textL">数量：{{ setFtNum(item, user, i) }}</div>
                                <div style="width: 100%;" class="textL">成本：{{ setFtPrice(item, user, i) }}</div>
                            </div>
                        </td>
						<td class="td" v-if="!isView">
							<!-- <el-icon @click="add()" v-if="index == 0" class="pointer" :size="24"><CirclePlusFilled /></el-icon> -->
							<el-icon @click="del(index)" class="pointer" :size="24"><RemoveFilled /></el-icon>
						</td>
					</tr>
					<tr class="tr">
						<td class="td" colspan="3">
							<div class="w100 textR">汇总</div>
						</td>
						<td class="td">
							{{ contentTotal }}
						</td>
						<td class="td">
							{{ contentPriceTotal }}
						</td>
                        <td class="td" v-for="user,i in chooseUserList" :key="i">
                            <div style="min-width: 120px;">
                                <div style="width: 100%;" class="textL">数量：{{ setFtNumTotal(user, i) }}</div>
                                <div style="width: 100%;" class="textL">成本：{{ setFtPriceTotal(user, i) }}</div>
                            </div>
                        </td>
						<td class="td" v-if="!isView">
							
						</td>
					</tr>
				</table>
			</div>
            <div class="flex mt10">
                <div v-if="!isView">快捷操作：</div>
                <div class="flex1">
                    <div v-if="!isView">
                        <el-button color="#333" size="small" @click="outInvent(1,6)">哑光6</el-button>
                        <el-button color="#333" size="small" @click="outInvent(1,8)">哑光8</el-button>
                        <el-button color="#333" size="small" @click="outInvent(1,12)">哑光12</el-button>
                        <el-button color="#48AAC5" size="small" @click="outInvent(2,6)">荧光6</el-button>
                        <el-button color="#48AAC5" size="small" @click="outInvent(2,8)">荧光8</el-button>
                        <el-button color="#48AAC5" size="small" @click="outInvent(2,12)">荧光12</el-button>
                        <el-button color="#F494AB" size="small" @click="outInvent(3,6)">珠光6</el-button>
                        <el-button color="#F494AB" size="small" @click="outInvent(3,8)">珠光8</el-button>
                        <el-button color="#F494AB" size="small" @click="outInvent(3,12)">珠光12</el-button>
                    </div>
                </div>
                <div style="padding-right: 15px;">
                    <el-icon v-if="!isView" @click="add()" class="pointer" :size="24"><CirclePlusFilled /></el-icon>
                </div>
            </div>
            <!-- <div class="textR pt5 pb5 bold font16" :style="{'padding-right': isView ? '115px' : '170px'}">采购总数：{{ contentTotal }}</div> -->
			<!-- <div class="flex flexL mt20">
				<div class="mr10">合计：</div>
				<div>
					<el-input v-model="totalAmount" disabled type="number" style="width: 120px;" />
				</div>
			</div> -->
		</el-form>
		<template #footer>
			<el-button @click="visible = false">{{ isView ? '关闭': '取消' }}</el-button>
			<el-button type="warning" @click="submitHandle(1)" :loading="btnloading" v-if="!isView && (dataForm.status==1||dataForm.status=='') && hasRule('admin/inventory/purchase/index/update')">保存草稿</el-button>
			<el-button type="primary" @click="submitHandle(-1)" :loading="btnloading" v-if="!isView && (dataForm.status==2) && hasRule('admin/inventory/purchase/index/update')">保存</el-button>
			<el-button type="primary" @click="submitHandle(2)" :loading="btnloading" v-if="!isView && (dataForm.status==1||dataForm.status=='') && hasRule('admin/inventory/purchase/index/update')">转为生产中</el-button>
			<el-button type="success" @click="submitHandle(3)" :loading="btnloading" v-if="!isView && (dataForm.status==2) &&  hasRule('admin/inventory/purchase/index/update')">转为入库单</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { Plus, Minus, CirclePlusFilled, RemoveFilled } from '@element-plus/icons-vue'
import { reactive, ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus/es'
import { getSupplierList, getCustomerList, getProductSkuList, addPurchase, getPurchase, addInventory } from '@/api/api'
import { Storage } from '@/utils/storage'
import { BASE_URL } from '@/config'
import { decrypt, encrypt, copy, timeResetDate, notNoNumber, hasRule } from '@/utils/tool'
import { departmentwithuser } from '@/api/org'

const isDevelopment = import.meta.env.MODE == 'development';
const emit = defineEmits(['refreshDataList'])
const typeList1 = ref([])
const supplierList = ref([])
const customerList = ref([])
const departmentList = ref([])
const isView = ref(false)
const productAllList = ref([])
const productList = ref([])
const visible = ref(false)
const btnloading = ref(false)
const pageloading = ref(false)
const canfilterable = ref(true)
const dataFormRef = ref()
const bindUrl = ref('')
const purchase_no = ref('')
const chooseUser = ref([])
const chooseUserList = ref([])

const dataForm = reactive({
	id: 0,
	remark: '',
	time: '',
	batch_no: '',
	type: '',
	out_type: '',
	status: '',
	supplier_name: '',
	customer_name: '',
	contents: '',
	order_sn: '',
})
const dataRules = ref({
	// time: [{ required: true, message: '必填项不能为空', trigger: ['blur','change'] }],
	// type: [{ required: true, message: '必填项不能为空', trigger: ['blur','change'] }],
	// supplier_name: [{ required: true, message: '必填项不能为空', trigger: ['blur','change'] }],
})
const totalAmount = ref('')
const options: any = ref([
    {
        productId: '',
        productName: '',
        inventory: 0,
        make_price: 0,
        quantity: '',
        attrList: [],
    }
])
const contentTotal = computed(() => {
    let total = options.value.reduce((to, it) => {
        return to + Number(it.quantity)
    }, 0);
    return Number((total).toFixed(4));
})
const contentPriceTotal = computed(() => {
    let total = options.value.reduce((to, it) => {
        return to + Number(it.quantity*it.make_price)
    }, 0);
    return Number((total).toFixed(4));
})
// 计算单品分摊总额
const setFtTotal = (item) => {
    if(item?.quantity){
        return Number((item.quantity*item.make_price).toFixed(4));
    }else{
        return 0;
    }
}
// 计算单品各自数量
const setFtNum = (item, user, idx) => {
    if(item?.quantity&&user?.rate){
        // 最后一列让前面的射出来计算
        if(idx == chooseUserList.value.length - 1) {
            const frontList = chooseUserList.value.slice(0, chooseUserList.value.length-1);
            const frontTotal = frontList.reduce((total, isss) => {
                return total + Number((item.quantity*isss.rate).toFixed(0))
            }, 0)
            return Number((item.quantity-frontTotal).toFixed(0));
        }else{
            return Number((item.quantity*user.rate).toFixed(0));
        }
    }else{
        return 0;
    }
}
// 计算单品各自成本
const setFtPrice = (item, user, idx) => {
    if(item?.quantity&&user?.rate){
        // 最后一列让前面的射出来计算
        if(idx == chooseUserList.value.length - 1) {
            const frontList = chooseUserList.value.slice(0, chooseUserList.value.length-1);
            const frontTotal = frontList.reduce((total, isss) => {
                return total + Number((item.quantity*isss.rate).toFixed(0))
            }, 0)
            return Number((item.quantity-frontTotal).toFixed(0)*item.make_price).toFixed(4);
        }else{
            return Number((item.quantity*user.rate).toFixed(0)*item.make_price).toFixed(4);
        }
    }else{
        return 0;
    }
}
// 计算总各自数量
const setFtNumTotal = (user, idx) => {
    if(user?.rate){
        if(idx == chooseUserList.value.length - 1){
            let frontTotal = 0;
            const frontList = chooseUserList.value.slice(0, chooseUserList.value.length-1);
            frontList.forEach(iiss => {
                const totalitem = options.value.reduce((total,item) => {
                    return total + Number((item.quantity*iiss.rate).toFixed(0));
                }, 0)
                frontTotal += totalitem;
            })
            return Math.floor(contentTotal.value - frontTotal);
        }else{
            const total = options.value.reduce((total,item) => {
                return total + Number((item.quantity*user.rate).toFixed(0));
            }, 0)
            return Number(total);
        }
    }else{
        return 0;
    }
}
// 计算总各自成本
const setFtPriceTotal = (user, idx) => {
    if(user?.rate){
        if(idx == chooseUserList.value.length - 1){
            let frontTotal = 0;
            const frontList = chooseUserList.value.slice(0, chooseUserList.value.length-1);
            frontList.forEach(iiss => {
                const totalitem = options.value.reduce((total,item) => {
                    return total + ((item.quantity*iiss.rate).toFixed(0)*item.make_price);
                }, 0)
                frontTotal += totalitem;
            })
            return Number(contentPriceTotal.value - frontTotal).toFixed(4);
        }else{
            const total = options.value.reduce((total,item) => {
                return total + ((item.quantity*user.rate).toFixed(0)*item.make_price);
            }, 0)
            return Number(total).toFixed(4);
        }
    }else{
        return 0;
    }
}
const disOption = (productName, fitem) => {
    if(fitem?.productName && productName != fitem.productName){
        return true;
    }else{
        return false;
    }
}
const handleChangeUser = (e) => {
    const clist = departmentList.value.filter(i => e.includes(i.id));
    clist.forEach(item => {
        if(item.id == 21){
            item.rate = 0.125;
        }
        if(item.id == 20){
            item.rate = 0.25;
        }
        if(item.id == 19){
            item.rate = 0.625;
        }
    })
    chooseUserList.value = clist?.map(i => {
        return {
            ...i,
            label: i.label,
            rate: i.rate||0,
        }
    })
    console.log(chooseUserList.value);
}
const add = () => {
	options.value.push(
        {
            productId: '',
            productName: '',
            make_price: 0,
            inventory: 0,
            quantity: '',
            attrList: [],
        }
    )
}
const del = (i) => {
	options.value.splice(i,1)
}
const setAmount = (i) => {
	// if (options.value[i].quantity || options.value[i].price) {
	// 	options.value[i].total_price = (options.value[i].quantity * options.value[i].price).toFixed(4)
	// }
}
const selectChange = (i, val) => {
    // console.log(i, val);
	if (val) {
		const list = productAllList.value.filter(i => i.name == val);
        list.sort((a,b)=>a.sort-b.sort);
        // console.log('list', list);
		options.value[i].attrList = list.map(item => {
            let label = item.attr_name_fill+'-'+item.attr_name;
            if(!item.attr_name_fill){
                label = item.attr_name;
            }
            return {
                ...item,
                label: label,
                value: item.id,
            }
        })
		options.value[i].productId = ''
	} else {
		options.value[i].productId = ''
	}
    // console.log(val, options.value[i]);
}
const selectChange2 = (i, val) => {
    // console.log(i, val);
	if (val) {
		const item = productAllList.value.find(i => i.id == val)
		options.value[i].make_price = item.make_price;
		options.value[i].inventory = item.inventory;
		options.value[i].product_type = item.type_name_fill+'-'+item.type_name;
		options.value[i].product_attr = item.attr_name_fill+'-'+item.attr_name;
	}
}
watch(() => options.value, (val) => {
	let total: any = 0
	total = options.value.reduce((price, item) => {
		return price + Number(item.total_price||0)
	}, 0)
	totalAmount.value = total.toFixed(4)
}, {
	deep: true
})
const getList = () => {
	return new Promise((resolve) => {
        getSupplierList({page:1,per_page:9999}).then((result) => {
            // console.log(result.data.data);
            supplierList.value = result.data.data.map((item) => {
                return {
                    ...item,
                    label: item.name,
                    value: item.id,
                }
            })
        }).catch((err) => {
            
        });
        departmentwithuser({}).then((result) => {
            console.log(result.data);
            departmentList.value = result.data.map((item) => {
                return {
                    ...item,
                    label: item.department_name,
                    value: item.id,
                }
            })
        }).catch((err) => {
            
        });
        getCustomerList({page:1,per_page:9999}).then((result) => {
            // console.log(result.data.data);
            customerList.value = result.data.data.map((item) => {
                return {
                    ...item,
                    label: item.name,
                    value: item.id,
                }
            })
        }).catch((err) => {
            
        });
        if(isView.value===true){
            setTimeout(()=>{
                resolve(true);
            }, 500)
        }else{
            getProductSkuList({page:1,per_page:9999}).then((result) => {
                // console.log(result.data.data);
                // 记录全部产品
                productAllList.value = result.data.data.reverse();
                // 去掉重复产品
                const onleList = [];
                productAllList.value.forEach(item => {
                    if (!onleList.some(i => i.label == item.name)) {
                        onleList.push({
                            label: item.name,
                            value: item.id,
                        })
                    }
                });
                productList.value = onleList;
                // console.log('productList.value', productList.value);
                resolve(true);
            }).catch((err) => {
            });
        }
    })
}
const init = async (id: any,type:any, v?: any, status?: any) => {
    const userinfo = Storage.getItem('userinfo');
    if(userinfo.strator_mobile=='13778948627' && window.innerWidth < 1920){
        canfilterable.value = false;
    }else{
        canfilterable.value = true;
    }
    chooseUser.value = [];
    chooseUserList.value = [];
    if (id) {
        dataForm.id = id;
	}else{
        dataForm.id = ''
    }
    dataForm.remark = ''
    dataForm.time = timeResetDate();
    dataForm.batch_no = ''
    dataForm.type = ''
    dataForm.out_type = ''
    if (status == 2) {
        dataForm.status = 2;
	}else{
        dataForm.status = ''
    }
    dataForm.supplier_name = ''
    dataForm.customer_name = ''
    dataForm.contents = ''
    dataForm.order_sn = ''
    options.value = [
        {
            productId: '',
            productName: '',
            inventory: 0,
            make_price: 0,
            quantity: '',
            attrList: [],
        }
    ]
	visible.value = true
	btnloading.value = false
	isView.value = v

	// 重置表单数据
	if (dataFormRef.value) {
		dataFormRef.value.resetFields()
	}
	// id 存在则为修改
	if (id) {
        pageloading.value = true;
        btnloading.value = true;
        await getList();
        pageloading.value = false;
        btnloading.value = false;
        dataForm.id = id;
		getDetail(id)
	}else{
        getList();
    }
}
// 获取信息
const getDetail = (id: number) => {
	getPurchase(id).then((res: any) => {
        // console.log('productAllList.value', productAllList.value);
        if (res.data.contents) {
            res.data.contents = JSON.parse(res.data.contents);
            console.log(res.data.contents);
            if(isView.value===true){
                // 去掉重复产品
                const onleList = [];
                res.data.contents.forEach(item => {
                    if (!onleList.some(i => i.label == item.productName)) {
                        onleList.push({
                            label: item.productName,
                            value: item.productId,
                        })
                    }
                });
                productList.value = onleList;
            }
            res.data.contents.forEach(item => {
                if (item.productName) {
                    if(isView.value===true){
                        item.attrList = [
                            {
                                label: item.product_attr,
                                value: item.productId,
                            }
                        ]
                    }else{
                        const list = productAllList.value.filter(i => i.name == item.productName)
                        item.attrList = list.map(item => {
                            return {
                                ...item,
                                label: item.attr_name_fill+'-'+item.attr_name,
                                value: item.id,
                            }
                        })
                    }
                }
                if (item.productId) {
                    if(isView.value===true){

                    }else{
                        const listItem = productAllList.value.find(i => i.id == item.productId)
                        item.inventory = listItem.inventory;
                        item.make_price = listItem.make_price;
                    }
                }
            })
            options.value = res.data.contents;
            // console.log(options.value);
        }
        if (res.data.share_contents) {
            res.data.share_contents = JSON.parse(res.data.share_contents);
            chooseUserList.value = res.data.share_contents;
            chooseUser.value = res.data.share_contents.map(i => i.id);
            // console.log(chooseUserList.value);
        }
        if(res.data.order_sn){
            purchase_no.value = res.data.order_sn;
        }
        delete res.data.created_at;
        delete res.data.updated_at;
        delete res.data.deleted_at;
		Object.assign(dataForm, res.data);
	})
}
// 表单提交
const submitHandle = (status) => {
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			return false
		}
		if (status != 1 && (!dataForm.time || !dataForm.supplier_name || options.value.some(i => !i.quantity || !i.productId || !i.productName))) {
			ElMessage.warning('请填写完整采购数据')
			return
		}
        const userinfo = Storage.getItem('userinfo');
		let params = {
			type: dataForm.type,
			operator: userinfo.strator_nickname,
			operator_id: userinfo.id,
            batch_no: dataForm.batch_no,
            remark: dataForm.remark,
		}
        const contents = JSON.parse(JSON.stringify(options.value));
        contents.forEach(item => {
            item.attrList = [];
        })
        // 采购单数据
        params.time = dataForm.time;
        params.type = dataForm.type;
        params.supplier_name = dataForm.supplier_name;
        params.status = status;
        params.contents = JSON.stringify(contents);
        if(chooseUserList.value?.length){
            params.share_contents = JSON.stringify(chooseUserList.value);
        }
		if (dataForm.id) {
            params.id = dataForm.id;
            params.updated_at = timeResetDate();
        } else {
            delete params.id;
        }
        console.log(params);
        // return;
        if (status == 2||status == 3) {
            ElMessageBox.confirm(`是否确定${status==2?'转为生产中':'转为入库单'}?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    btnloading.value = true;
                    addPurchase(params)
                        .then((res: any) => {
                            if (res.status == 'success') {
                                if(status == 3){
                                    const addParams = {
                                        type: 1,
                                        in_type: params.type,
                                        operator: params.operator,
                                        operator_id: params.operator_id,
                                        in_time: timeResetDate(),
                                        batch_no: params.batch_no,
                                        // remark: params.remark,
                                        supplier_name: params.supplier_name,
                                        contents: params.contents,
                                        share_contents: params.share_contents,
                                        purchase_no: purchase_no.value,
                                        status: 1,
                                    }
                                    addInventory(addParams).then((res: any) => {
                                        if (res.status == 'success') {
                                            ElMessage.success({
                                                message: params.id?'编辑成功':'添加成功',
                                                duration: 500,
                                                onClose: () => {
                                                    visible.value = false
                                                    emit('refreshDataList')
                                                }
                                            })
                                        } else {
                                            btnloading.value = false
                                            ElMessage.error({
                                                message: res.message || '提交失败',
                                                duration: 1200
                                            })
                                        }
                                    })
                                    .catch(() => {
                                        btnloading.value = false
                                    })
                                }else{
                                    ElMessage.success({
                                        message: params.id?'编辑成功':'添加成功',
                                        duration: 500,
                                        onClose: () => {
                                            visible.value = false
                                            emit('refreshDataList')
                                        }
                                    })
                                }
                            } else {
                                btnloading.value = false
                                ElMessage.error({
                                    message: res.message || '提交失败',
                                    duration: 1200
                                })
                            }
                        })
                        .catch(() => {
                            btnloading.value = false
                        })
                })
        } else {
            btnloading.value = true;
            if(params.status==-1){
                params.status = 2;
            }
            addPurchase(params)
                .then((res: any) => {
                    btnloading.value = false;
                    if (res.status == 'success') {
                        ElMessage.success({
                            message: params.id?'编辑成功':'添加成功',
                            duration: 500,
                            onClose: () => {
                                visible.value = false
                                emit('refreshDataList')
                            }
                        })
                    } else {
                        btnloading.value = false
                        ElMessage.error({
                            message: res.message || '提交失败',
                            duration: 1200
                        })
                    }
                })
                .catch(() => {
                    btnloading.value = false
                })
        }
	})
}
// type：1哑光，2荧光，3珠光，len颜色数量
const outInvent = (type, len) => {
    const num = prompt("输入出库数量(默认为空)","");
    let nowIndexOld = options.value.length;
    let nowIndex = options.value.length;
    let idList = [];
    let lenList = [];
    if(type==1){
        idList = [3,8,4,6,7,10,5,11,9,12,14,13];
        if(len==12){
            lenList = [3,8,4,6,7,10,5,11,9,12,14,13];
        }else{
            lenList = [3,8,4,6,7,5,10,9,11,12,14,13];
        }
    }
    if(type==2){
        idList = [27,32,28,30,31,34,29,38,33,37,36,35];
        if(len==12){
            lenList = [27,32,28,30,31,34,29,38,33,37,36,35];
        }else{
            lenList = [27,32,28,30,31,29,34,33,38,37,36,35];
        }
    }
    if(type==3){
        idList = [15,20,16,18,19,22,17,23,21,26,24,25];
        if(len==12){
            lenList = [15,20,16,18,19,22,17,23,21,26,24,25];
        }else{
            lenList = [15,20,16,18,19,17,22,21,23,26,24,25];
        }
    }
    if(num === null){
        return;
    }
    let timex = 0;
    let idx = 0;
    let timer = setInterval(()=>{
        timex++;
        if(timex > len){
            timex = 0;
            clearInterval(timer);
            setTimeout(()=>{
                if(!options.value[0].productName){
                    options.value.splice(0,1);
                }else if(options.value.some(i => i.productName != '心型染发夹')){
                    options.value.splice(0,nowIndexOld);
                }
            },400)
            return;
        }
        options.value.push(
            {
                productId: '',
                productName: '',
                inventory: 0,
                make_price: 0,
                quantity: num || '',
                attrList: [],
            }
        )
        setTimeout(()=>{
            // console.log('nowIndex',nowIndex);
            options.value[nowIndex].productName = '心型染发夹';
            selectChange(nowIndex, '心型染发夹');
        }, 150)
        setTimeout(()=>{
            options.value[nowIndex].productId = lenList[idx];
            selectChange2(nowIndex, lenList[idx]);
            idx++;
            nowIndex++;
        }, 300)
    }, 450)
}
defineExpose({
	init
})
</script>
<style lang="scss" scoped>
:deep(){
    .el-date-editor {
        .el-input__wrapper {
            width: 100%;
            box-sizing: border-box;
        }
    }
}
</style>